
#include "arrayctrl.h"
#include "strctrl.h"

//Skip delimeter in srcStr
//
//Parameter:
//	srcStr		Source string
//	delim 		String which need to be skiped		
//Return:
//	Address of the new start in the source string
//
char * skipstr(char * srcStr, char * delim)
{
	char * pos = strstr(srcStr, delim);
	if (pos != NULL)
	{
		pos += strlen(delim);
		return pos;
	}
	else
	{
		return NULL;
	}
}

//Dump sub string to string buffer
//
//Parameter:
//	stcStr		Source string
//	delim 		Delimeter for end of sub string
//	destBuf		Output buffer for dumped sub string
//Return:
//	Address in source strong after the first delimeter
//
char *token(char * srcStr, char * delim, char * destBuf)
{
	char * pos = strstr(srcStr, delim);
	if (pos != NULL)
	{
		int len = (int)pos - (int)srcStr;
		memset(destBuf, 0, len + 1);
		memcpy(destBuf, srcStr, len);
		pos += strlen(delim);
		return pos;
	}
	else
	{
		strcpy(destBuf, srcStr);
		return NULL;
	}
}

//Cut the spaces in front and end of the source string
//
//Parameter:
//	srcStr		Source string
//	desfBuf		Output buffer for cutted string
//Return:
//	Start address in source string 
//
char * trim(char * srcStr, char * destBuf)
{
	while ((*srcStr != '\0') && (srcStr) && (*srcStr == ' '))
	{
		srcStr++;
	}
	
	if (srcStr)
	{
		int len = strlen(srcStr);
		char * pos;
		pos = srcStr + len - 1;
		while ((srcStr >= pos) && (pos) && (*pos == ' '))
		{
			pos--;
		}
		len = pos - srcStr + 1;
	
		memset(destBuf, 0, len + 1);
		memcpy(destBuf, srcStr, len);
		return srcStr;
	}
	else
	{
		return NULL;
	}
}

//Convert string to unsigned integer value
//
//Parameter:
//	buf 			Input string
//
//Return:
//	Converted unsigned integer value
//
uint32 struint(char * buf)
{
	char *v = buf;
	uint32 val = 0;
	while((v) && (*v <= '9') && (*v >= '0'))
	{
		val = val * 10 + (*v - '0');
		v++;
	}
	return val;
}

//Call back function to release string resource in dynamic array (see dynamic array)
//
//Parameter:
//	obj				Object reference
//Return:
//	None
//
void OnAC_StringDestroy(void *obj)
{
	if (obj)
	{
		free(obj);
	}
}

//Split string into dynamic array list by delimeter
//
//Parameter:
//	srcStr		Source string
//	delim			Delimeter
//Return:
//	Handle of dynamic array which is used to store splitted sub strings
//
ACHANDLE strsplit(char * srcStr, char * delim)
{
	ACHANDLE handle = AC_Create(OnAC_StringDestroy);
	char buf[SC_MAX_BUF];
	char * ch, * pos = srcStr;
	int len;
	while(pos)
	{
		pos = token(pos, delim, buf);
		if ((len = strlen(buf)) > 0)
		{
			ch = malloc(len + 1);
			strcpy(ch, buf);
			AC_Add(handle, ch);
		}
	}
	return handle;
}

